﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;

using CodeKicker.BBCode;

using mvcForum.Web.Interfaces;

namespace mvcForum.AddOns.ContentParsing {

	public class BBCParser : IContentParser {

		public MvcHtmlString Parse(String content) {
			return MvcHtmlString.Create(BBCodeToHTML(content));
		}

		private static String BBCodeToHTML(String text) {
			// TODO: Load these tags from somewhere ???
			return BBCodeToHTML(text, new[]
                {
                    new BBTag("b", "<b>", "</b>"), 
                    new BBTag("i", "<i>", "</i>"), 
                    new BBTag("u", "<u>", "</u>"), 
                    new BBTag("strike", "<span style=\"text-decoration: line-through;\">", "</span>"), 
                    new BBTag("code", "<div class=\"ca-bbcode\"><div class=\"ca-bbcode2 ca-code\"><dl class=\"codebox\"><dt>Code:</dt><dd><code>", "</code></dd></dl></div></div>"), 
                    new BBTag("img", "<img src=\"${content}\" />", "", false, true), 
                    new BBTag("quote", "<div class=\"ca-bbcode\"><div class=\"ca-bbcode2 ca-quote\"><blockquote><div><cite>${user} wrote:</cite>", "</div></blockquote></div></div>", new BBAttribute("user", ""), new BBAttribute("user", "user")), 
                    new BBTag("list", "<ul>", "</ul>", new BBAttribute("class", "")), 
                    new BBTag("list=1", "<ol>", "</ol>", new BBAttribute("class", "")), 
                    new BBTag("*", "<li>", "</li>", true, false), 
                    new BBTag("url", "<a href=\"${href}\">", "</a>", new BBAttribute("href", ""), new BBAttribute("href", "href")), 
                });
		}

		private static String BBCodeToHTML(String text, IList<BBTag> tags) {
			BBCodeParser parser = new BBCodeParser(ErrorMode.ErrorFree, tags);

			// Let's sanitize the input, we don't want HTML to get past the parser and into the output!
			//return parser.ToHtml(text.SanitizeHTML()).Replace(Environment.NewLine, "<br />");
			return parser.ToHtml(text).Replace(Environment.NewLine, "<br />");
			//return parser.ToHtml(text.Replace("<", "&lt;").Replace(">", "&gt;")).Replace(Environment.NewLine, "<br />");
		}

		public String Quote(String author, String content) {
			return String.Format("[quote={0}]{1}[/quote]", author, content);
		}

		public String Name {
			get {
				return "BBCode";
			}
		}
	}
}